"""
Flask路由模块
包含所有webhook相关的路由处理
"""

import logging
import urllib.parse
import xml.etree.ElementTree as ET
from flask import request, jsonify

logger = logging.getLogger(__name__)

class WebhookRoutes:
    """Webhook路由处理器"""
    
    def __init__(self, app, bot):
        """
        初始化路由处理器
        
        Args:
            app: Flask应用实例
            bot: 机器人实例
        """
        self.app = app
        self.bot = bot
        self.register_routes()
    
    def register_routes(self):
        """注册所有路由"""
        
        @self.app.route('/webhook', methods=['GET', 'POST'])
        def webhook():
            """处理企业微信webhook请求"""
            try:
                if request.method == 'GET':
                    # 打印所有收到的参数
                    logger.info(f"收到企业微信GET验证请求: {dict(request.args)}")
                    print("收到企业微信GET验证请求:", dict(request.args))
                    
                    # URL验证请求
                    msg_signature = request.args.get('msg_signature', '')
                    timestamp = request.args.get('timestamp', '')
                    nonce = request.args.get('nonce', '')
                    echostr = request.args.get('echostr', '')
                    
                    # 对参数进行URL解码（企业微信官方要求）
                    msg_signature = urllib.parse.unquote(msg_signature)
                    timestamp = urllib.parse.unquote(timestamp)
                    nonce = urllib.parse.unquote(nonce)
                    echostr = urllib.parse.unquote(echostr)
                    
                    logger.info(f"收到URL验证请求: msg_signature={msg_signature}, timestamp={timestamp}, nonce={nonce}")
                    
                    if not all([msg_signature, timestamp, nonce, echostr]):
                        return "参数不完整", 400
                    
                    # 验证URL
                    decrypted_echostr = self.bot.verify_url(msg_signature, timestamp, nonce, echostr)
                    if decrypted_echostr:
                        logger.info("URL验证成功")
                        return decrypted_echostr
                    else:
                        logger.error("URL验证失败")
                        return "验证失败", 403
                        
                elif request.method == 'POST':
                    # 消息接收请求
                    msg_signature = request.args.get('msg_signature', '')
                    timestamp = request.args.get('timestamp', '')
                    nonce = request.args.get('nonce', '')
                    
                    # 对参数进行URL解码（企业微信官方要求）
                    msg_signature = urllib.parse.unquote(msg_signature)
                    timestamp = urllib.parse.unquote(timestamp)
                    nonce = urllib.parse.unquote(nonce)
                    
                    logger.info(f"收到消息请求: msg_signature={msg_signature}, timestamp={timestamp}, nonce={nonce}")
                    
                    # 获取请求体
                    body = request.get_data(as_text=True)
                    logger.info(f"请求体: {body}")
                    
                    # 解析XML
                    try:
                        root = ET.fromstring(body)
                        encrypted_msg = root.find('Encrypt').text
                    except Exception as e:
                        logger.error(f"解析XML失败: {str(e)}")
                        return "XML解析失败", 400
                    
                    # 解密消息
                    decrypted_xml = self.bot.decrypt_message(msg_signature, timestamp, nonce, encrypted_msg)
                    if not decrypted_xml:
                        logger.error("消息解密失败")
                        return "消息解密失败", 403
                    
                    # 解析解密后的XML
                    message_data = self.bot.parse_xml_message(decrypted_xml)
                    if not message_data:
                        logger.error("解析消息失败")
                        return "消息解析失败", 400
                    
                    # 消息去重检查 - 使用更精确的标识符
                    event_id = f"{message_data.get('create_time', '')}_{message_data.get('msg_id', '')}"
                    if event_id:
                        if event_id in self.bot.message_handler.processed_messages:
                            logger.info(f"重复事件，跳过处理: {event_id}")
                            return "success"
                        else:
                            # 添加到已处理列表
                            self.bot.message_handler.processed_messages.add(event_id)
                            # 限制缓存大小
                            if len(self.bot.message_handler.processed_messages) > self.bot.message_handler.max_cache_size:
                                self.bot.message_handler.processed_messages.clear()
                    
                    # 处理消息并立即返回success，避免企业微信重试
                    response_text = self.bot.process_message(message_data)
                    
                    # 只记录处理结果，不发送到群机器人
                    if response_text:
                        logger.info(f"消息处理完成: {response_text}")
                    
                    # 立即返回success，告诉企业微信消息已收到
                    return "success"
                        
            except Exception as e:
                logger.error(f"处理webhook请求时发生错误: {str(e)}")
                return "内部服务器错误", 500
        
        @self.app.route('/health', methods=['GET'])
        def health_check():
            """健康检查"""
            return jsonify({
                'status': 'healthy', 
                'service': 'wechat-bot',
                'version': '2.0 (模块化版本)'
            })
        
        @self.app.route('/', methods=['GET'])
        def index():
            """首页"""
            return """
            <h1>企业微信群机器人</h1>
            <p>状态: 运行中</p>
            <p>配置信息:</p>
            <ul>
                <li>Webhook URL: {}</li>
                <li>企业微信加解密: {}</li>
                <li>AI API: 已配置（使用llm.py）</li>
            </ul>
            """.format(
                "已配置" if self.bot.config.WEBHOOK_URL else "未配置",
                "已配置" if self.bot.wx_crypto else "未配置"
            )
        
        @self.app.route('/status', methods=['GET'])
        def status():
            """状态检查"""
            try:
                # 检查各个组件状态
                status_info = {
                    'service': '企业微信群机器人',
                    'version': '2.0 (模块化版本)',
                    'status': 'running',
                    'components': {
                        'wx_crypto': '✅ 正常' if self.bot.wx_crypto else '❌ 未配置',
                        'wx_api': '✅ 正常' if self.bot.wx_api else '❌ 未配置',
                        'message_handler': '✅ 正常' if self.bot.message_handler else '❌ 未配置',
                        'llm': '✅ 正常'  # 假设LLM模块总是可用的
                    },
                    'config': {
                        'webhook_url': self.bot.config.WEBHOOK_URL,
                        'host': self.bot.config.HOST,
                        'port': self.bot.config.PORT
                    }
                }
                return jsonify(status_info)
            except Exception as e:
                logger.error(f"状态检查失败: {str(e)}")
                return jsonify({'error': str(e)}), 500
        
        @self.app.route('/test', methods=['GET'])
        def test():
            """测试接口"""
            try:
                # 测试AI API
                test_message = "你好，这是一个测试消息"
                ai_response = self.bot.call_ai_api(test_message)
                
                return jsonify({
                    'test': 'success',
                    'message': test_message,
                    'ai_response': ai_response,
                    'timestamp': self.bot.get_current_timestamp()
                })
            except Exception as e:
                logger.error(f"测试失败: {str(e)}")
                return jsonify({'error': str(e)}), 500 

        @self.app.route('/api/switch_to_ai', methods=['POST'])
        def switch_to_ai():
            """
            手动将会话转回AI服务
            
            POST参数:
            - customer_id: 客户ID
            - servicer_id: 人工客服ID（可选，用于验证）
            
            Returns:
            - success: 是否成功
            - message: 结果消息
            """
            try:
                data = request.get_json()
                customer_id = data.get('customer_id')
                servicer_id = data.get('servicer_id')
                
                if not customer_id:
                    return jsonify({
                        'success': False,
                        'message': '缺少客户ID参数'
                    }), 400
                
                # 获取对话管理器
                from handlers.conversation_manager import ConversationManager
                conversation_manager = ConversationManager()
                
                # 检查当前会话状态
                is_human_service = conversation_manager.is_currently_human_service(customer_id)
                
                if not is_human_service:
                    return jsonify({
                        'success': False,
                        'message': '客户当前不在人工服务状态'
                    }), 400
                
                # 执行转回AI操作
                conversation_manager.switch_back_to_ai(customer_id)
                
                logger.info(f"👤 人工客服 {servicer_id} 手动将会话转回AI，客户: {customer_id}")
                
                return jsonify({
                    'success': True,
                    'message': f'客户 {customer_id} 已成功转回AI服务',
                    'customer_id': customer_id,
                    'switched_by': servicer_id
                })
                
            except Exception as e:
                logger.error(f"转回AI服务失败: {str(e)}")
                return jsonify({
                    'success': False,
                    'message': f'转回AI服务失败: {str(e)}'
                }), 500

        @self.app.route('/api/session_status/<customer_id>', methods=['GET'])
        def get_session_status(customer_id):
            """
            获取客户会话状态
            
            Args:
            - customer_id: 客户ID
            
            Returns:
            - session_info: 会话信息
            """
            try:
                from handlers.conversation_manager import ConversationManager
                conversation_manager = ConversationManager()
                
                session = conversation_manager.get_or_create_session(customer_id)
                
                session_info = {
                    'customer_id': customer_id,
                    'is_human_service': session.is_human_service,
                    'human_service_start': session.human_service_start.isoformat() if session.human_service_start else None,
                    'auto_switch_back_time': session.auto_switch_back_time.isoformat() if session.auto_switch_back_time else None,
                    'last_activity': session.last_activity.isoformat(),
                    'conversation_count': len(session.conversation_items)
                }
                
                return jsonify({
                    'success': True,
                    'session_info': session_info
                })
                
            except Exception as e:
                logger.error(f"获取会话状态失败: {str(e)}")
                return jsonify({
                    'success': False,
                    'message': f'获取会话状态失败: {str(e)}'
                }), 500 